<!-- ArticleDetail.vue -->
<template>
  <div class="article-detail" v-if="article">
    <div class="header">
      <el-button @click="router.back()">返回</el-button>
      
    </div>

    <div v-if="loading" class="loading">
      <el-skeleton :rows="10" animated />
    </div>

    <div v-else-if="error" class="error">
      <el-alert :title="error" type="error" />
    </div>

    <div v-else class="article-content">
      <h1 class="title">{{ article.title }}</h1>
      
      <div class="meta">
        <span>作者: {{ article.author }}</span>
        <span>发布时间: {{ formatDate(article.createTime) }}</span>
        <span>更新时间: {{ formatDate(article.updateTime) }}</span>
        <span>状态: {{ article.status === 1 ? '已发布' : '草稿' }}</span>
      </div>

      <div class="cover" v-if="article.coverImage">
        <img :src="article.coverImage" :alt="article.title">
      </div>

      <div class="content" v-html="article.content"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessageBox } from 'element-plus';
import { useArticleStore } from '../store/article';
import { storeToRefs } from 'pinia';

const route = useRoute();
const router = useRouter();
const articleStore = useArticleStore();
const { currentArticle: article, loading, error } = storeToRefs(articleStore);

onMounted(async () => {
  const id = route.params.id as string;
  await articleStore.fetchArticleById(id);
});

const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleDateString('zh-CN');
};

const handleEdit = (): void => {
  if (article.value) {
    router.push(`/article/edit/${article.value.id}`);
  }
};

const handleDelete = async (): Promise<void> => {
  if (!article.value) return;

  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await articleStore.deleteArticle(article.value.id);
    router.push('/');
  } catch {
    // 用户取消删除操作
  }
};
</script>

<style scoped>
.article-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.actions {
  display: flex;
  gap: 10px;
}

.loading, .error {
  margin: 20px 0;
}

.title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.meta {
  color: #999;
  font-size: 14px;
  margin-bottom: 20px;
}

.meta span {
  margin-right: 20px;
}

.cover {
  margin-bottom: 20px;
}

.cover img {
  max-width: 100%;
  height: auto;
}

.content {
  line-height: 1.8;
  color: #333;
}

:deep(.content img) {
  max-width: 100%;
  height: auto;
}
</style>